<template>
    <div class="doc_share_container" ref="mainContainer">
        <el-container>
            <el-header>
                <div class="header_span" ref="containerHeader">
                    <div class="header_title">{{ docInfo.title }}</div>
                </div>
            </el-header>
            <el-container>
                <!-- left -->
                <el-aside width="260px" class="show_span_pc">
                    <div class="menu_top_span" :style="{height: menuTopHeight + 'px'}">
                        <div class="menu_top_span_item bt_menu_search" @click="openSearchDialog">
                            <i class="fa-solid fa-magnifying-glass"></i>
                            <span>搜索</span>
                        </div>
                        <div class="menu_top_span_item menu_top_catalog">
                            <span>目录</span>
                            <div class="menu_top_catalog_bt">
                                <span @click="menuLocation">
                                    <i class="fa-solid fa-location-crosshairs"></i>
                                </span>
                                <span v-show="!menuUnfold" @click="meneUnfoldOperate">
                                    <i class="fa-solid fa-folder"></i>
                                </span>
                                <span v-show="menuUnfold" @click="meneUnfoldOperate">
                                    <i class="fa-solid fa-folder-tree"></i>
                                </span>
                            </div>
                        </div>   
                    </div>
                    <div :style="{width: '100%',height: scrollbarHeight + 'px'}">
                        <el-scrollbar :height="scrollbarHeight" class="doc_left_scroll">
                            <el-menu :unique-opened="false" @select="menuItemSelect" :default-active="defaultActive"
                                class="doc_menu" ref="chapterMenu">
                                <CustomMenuItem :children="docInfo.chapterList"></CustomMenuItem>
                            </el-menu>
                        </el-scrollbar>
                    </div>
                </el-aside>
                <div class="show_span_mobile">
                    <el-drawer v-model="mobileMenuShow" :with-header="false" direction="ltr" size="260px">
                        <div class="menu_top_span" :style="{height: menuTopHeight + 'px'}">
                            <div class="menu_top_span_item bt_menu_search" @click="openSearchDialog">
                                <i class="fa-solid fa-magnifying-glass"></i>
                                <span>搜索</span>
                            </div>
                            <div class="menu_top_span_item menu_top_catalog">
                                <span>目录</span>
                                <div class="menu_top_catalog_bt">
                                    <span @click="menuLocation">
                                        <i class="fa-solid fa-location-crosshairs"></i>
                                    </span>
                                    <span v-show="!menuUnfold" @click="meneUnfoldOperate">
                                        <i class="fa-solid fa-folder"></i>
                                    </span>
                                    <span v-show="menuUnfold" @click="meneUnfoldOperate">
                                        <i class="fa-solid fa-folder-tree"></i>
                                    </span>
                                </div>
                            </div>   
                        </div>
                        <div :style="{width: '100%',height: mobileScrollbarHeight + 'px'}">
                            <el-scrollbar :height="mobileScrollbarHeight" class="doc_left_scroll">
                                <el-menu :unique-opened="false" @select="menuItemSelect" :default-active="defaultActive"
                                    class="doc_menu" ref="chapterMenu">
                                    <CustomMenuItem :children="docInfo.chapterList"></CustomMenuItem>
                                </el-menu>
                            </el-scrollbar>
                        </div>
                        <div class="doc_menu_bottom" :style="{height: menuBottomHeight + 'px'}" @click="showMobileMenu">
                            <i class="fas fa-angles-left"></i>
                        </div>
                    </el-drawer>
                </div>
                <!-- main -->
                <el-main style="--el-main-padding:0px;overflow: hidden;" ref="mainSpanRef">
                    <div class="navigation_bar_span">
                        <el-breadcrumb separator-icon="ArrowRight" class="show_span_pc">
                            <el-breadcrumb-item v-for="item in breadcrumbList">{{item}}</el-breadcrumb-item>
                        </el-breadcrumb>
                        <div class="menu_bt_span show_span_mobile" @click="showMobileMenu">
                            <i class="fas fa-bars"></i>
                        </div>
                    </div>
                    <div class="content_span">
                        <el-scrollbar :height="docScrollbarHeight">
                            <div id="editor-container" :style="{height: docScrollbarHeight + 'px'}"></div>
                        </el-scrollbar>
                    </div>
                </el-main>
            </el-container>
        </el-container>
        <el-dialog title="内容搜索" v-model="searchDialogOption.isShow" :width="searchDialogOption.width"
        :close-on-click-modal="false" :close-on-press-escape="false"
        @close="searchDialogClose" center>
            <div class="search_dialog_span">
                <div class="search_dialog_top">
                    <el-input v-model="searchDialogOption.searchContent" placeholder="内容搜索" clearable 
                    @change="changeSearchCondition"
                    @clear="clearSearchCondition">
                        <template #prefix>
                            <el-icon class="el-input__icon"><search /></el-icon>
                        </template>
                        <template #suffix>
                            <el-link type="primary" :underline="false" @click="btSearch">搜索</el-link>
                        </template>
                    </el-input>
                </div>
                <div class="search_dialog_center">
                    <el-scrollbar height="320px" style="width: 100%;">
                        <ul class="search_list">
                            <li class="search_list_item" v-for="item in searchList" @click="selectSearchResult(item)">
                                <div class="search_doc_span">
                                    <div class="search_doc_span_item search_doc_title">
                                        <span class="search_doc_title_ico">
                                            <i class="far fa-file-lines"></i>
                                        </span>
                                        {{item.title}}
                                    </div>
                                    <div class="search_doc_span_item search_doc_date">{{item.updateTime}}</div>
                                </div>
                                <div class="search_doc_result" v-if="item.contentText" v-html="item.contentText"></div>
                            </li>
                        </ul>
                    </el-scrollbar>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css'
import { tool } from "@/js/tool.js";
import { ElMessage } from 'element-plus'
import CustomMenuItem from '@/components/custom-menu-item.vue';
import { createEditor } from '@wangeditor/editor/dist/index.js';

const editorConfig = { 
    placeholder: '', 
    autoFocus: false,
    readOnly: true, 
    scroll: false
}

export default {
    name: "docShare",
    data: function () {
        return {
            shareCode: null,
            docInfo: {
                title: null,
                shareCode: null,
                chapterList: null
            },
            chapterMap: {},
            scrollbarHeight: 200,
            mobileScrollbarHeight: 200,
            docScrollbarHeight: 500,
            defaultActive: '',
            breadcrumbList: null,
            selectChapter: null,
            docContent: null,
            editor: null,

            searchDialogOption: {
                isShow: false,
                width: 200,
                searchContent: null
            },
            searchList: [],
            menuTopHeight: 80,
            menuBottomHeight: 20,
            menuUnfold: false, // true展开；false折叠
            mobileMenuShow: false
        }
    },
    methods: {
        menuItemSelect: function (index, indexPath, item) {
            this.breadcrumbList = new Array();
            for (let i = 0; i < indexPath.length; i++) {
                this.breadcrumbList.push(this.chapterMap[indexPath[i]].title);
            }
            this.selectChapter = this.chapterMap[index];
            this.defaultActive = index;
            getDocContent(this);
        },
        showMobileMenu: function(){
            if(this.mobileMenuShow){
                this.mobileMenuShow = false;
            }else{
                this.mobileMenuShow = true;
            }
        },
        meneUnfoldOperate: function(){
            foldOrUnfold(this);
            this.menuUnfold = !(this.menuUnfold);
        },
        menuLocation: function(){
            const indexPath = this.selectChapter.indexPath;
            if(indexPath == null || indexPath.length <= 1){
                return;
            }
            for(let i=0;i<indexPath.length - 1; i++){
                this.$refs['chapterMenu'].open(indexPath[i]);
            }
            this.menuUnfold = true;
        },
        openSearchDialog: function(){
            this.searchDialogOption.isShow = true;
            setSearchDefaultList(this);
        },
        changeSearchCondition: function(value){
            if(value == null || value == ''){
                setSearchDefaultList(this);
            }
        },
        clearSearchCondition: function(){
            setSearchDefaultList(this);
        },
        searchDialogClose: function(){
            this.searchDialogOption.searchContent = null;
            this.searchList = [];
        },
        btSearch: function(){
            this.searchList = [];
            searchContent(this);
        },
        selectSearchResult: function(value){
            setSelectChapter(this, value.treeIndex);
            this.searchDialogOption.isShow = false;
        }
    },
    created: function () {
        this.shareCode = this.$route.query.shareCode;
        if (!this.shareCode) {
            ElMessage({
                showClose: true,
                message: '未查询到文档信息',
                type: 'error'
            });
            return;
        }
    },
    mounted: function () {
        calcScrollerHeight(this);
        getDocInfo(this);
        calcWidth(this);
    },
    components: {
        CustomMenuItem
    }
}

/**
 * 设置默认的查询列表
 */
function setSearchDefaultList(app){
    app.searchList = new Array();
    for(let item in app.chapterMap){
        let chapter = app.chapterMap[item];
        if(chapter.type == 1){
            app.searchList.push(chapter);
        }
    }
}

/**
 * 展开或者折叠所有的菜单
 */
function foldOrUnfold(app){
    for(let index in app.chapterMap){
        let item = app.chapterMap[index];
        if(item.type == 0){
            if(app.menuUnfold){
                app.$refs['chapterMenu'].close(index);
            }else{
                app.$refs['chapterMenu'].open(index);
            }
        }
    }
}

/**
 * 初始化编辑器
 */
 function createEditorInit(app, content){
    const editor = createEditor({
        selector: '#editor-container',
        html: content,
        config: editorConfig,
        mode: 'simple'
    });
    app.editor = editor;
}

/**
 * 选择章节内容
 */
function setSelectChapter(app, treeIndex){
    const selectMenu = app.chapterMap[treeIndex];
    if(selectMenu.type == 0){
        return;
    }
    app.selectChapter = selectMenu;

    app.defaultActive = treeIndex;

    app.breadcrumbList = new Array();
    getDocContent(app);
}

/**
 * 设置默认的章节目录
 */
function setDefaultChapter(app) {
    for(let index in app.chapterMap){
        let chapter = app.chapterMap[index];
        if(chapter.type == 1){
            app.defaultActive = chapter.treeIndex;
            app.breadcrumbList = new Array();
            const selectMenu = app.chapterMap[app.defaultActive];
            for(let i=0;i<selectMenu.indexPath.length;i++){
                app.breadcrumbList.push(app.chapterMap[selectMenu.indexPath[i]].title);
            }
            //默认选择的内容
            app.selectChapter = selectMenu;
            getDocContent(app);
            break;
        }
    }
}

/**
 * 计算屏幕宽度
 */
function calcWidth(app){
    const screenWidth = window.innerWidth;
    if(screenWidth <= 400){
        app.searchDialogOption.width = '96%';
    }else if(screenWidth > 400 && screenWidth <= 720){
        app.searchDialogOption.width = 420;
    }else {
        app.searchDialogOption.width = 640;
    }
}

/**
 * 计算滚动条的高度
 */
function calcScrollerHeight(app) {
    const height = app.$refs['mainContainer'].offsetHeight;
    const headerHeight = app.$refs['containerHeader'].offsetHeight;

    app.scrollbarHeight = height - headerHeight - app.menuTopHeight - 2; // 左测高度

    app.docScrollbarHeight = height - headerHeight - 33;

    app.menuBottomHeight = headerHeight - 20;

    //移动端高度
    app.mobileScrollbarHeight = height - app.menuTopHeight - app.menuBottomHeight;
}

/**
 * 获取章节列表
 */
function getDocInfo(app) {
    const url = "/doc/share/" + app.shareCode;
    tool.getRequest(url, null, function (data) {
        if (data.code === "0000") {
            app.docInfo = data.data;

            setChapterMap(app); 
            const treeIndex = app.$route.query.treeIndex;
            if(treeIndex){
                setSelectChapter(app, treeIndex);
            }else{
                setDefaultChapter(app);
            }
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 获取文档内容
 */
 function getDocContent(app) {
    if(app.editor != null){
        app.editor.destroy();
    }
    if(!app.selectChapter.contentIndex){
        app.docContent = "";
        return;
    }
    const url = "/doc/share/content/" + app.shareCode + "?index=" + app.selectChapter.contentIndex;
    tool.formRequest(url, null, null, function (data) {
        if (data.code === "0000") {
            app.docContent = data.data.content;
            if(app.docContent == null){
                app.docContent = "";
            }
            createEditorInit(app, app.docContent);
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 查询内容
 */
function searchContent(app){
    const searchContent = app.searchDialogOption.searchContent;
    if(!searchContent){
        return;
    }
    const url = "/doc/share/content/search/" + app.shareCode + "?content=" + searchContent;
    tool.formRequest(url, null, null, function (data) {
        if (data.code === "0000") {
            for(let i=0; i < data.data.length; i++){
                let resultItem = data.data[i];
                for(let item in app.chapterMap){
                    let chapter = app.chapterMap[item];
                    if(resultItem.documentId == chapter.contentIndex){
                        let showItem = {
                            contentText: resultItem.contentText,
                            treeIndex: chapter.treeIndex,
                            title: chapter.title
                        }
                        app.searchList.push(showItem);
                    }
                }
            }
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 将章节的树状层级转成Key-Value形式方便查询。
 * 优先深度查询
 * key：treeIndex
 */
function setChapterMap(app) {
    app.chapterMap = {}
    for (let i = 0; i < app.docInfo.chapterList.length; i++) {
        let item = app.docInfo.chapterList[i];
        item['indexPath'] = [item.treeIndex];
        app.chapterMap[item.treeIndex] = item;
        if (item.children != null && item.children.length > 0) {
            setChapterChildrenMap(item.children, app.chapterMap, item);
        }
    }
}

/**
 * 递归获取子列表的数据。
 */
function setChapterChildrenMap(chapterList, map, parent) {
    for (let i = 0; i < chapterList.length; i++) {
        let item = chapterList[i];
        const temp = parent.indexPath.slice(0);
        temp.push(item.treeIndex);
        item['indexPath'] = temp;
        map[item.treeIndex] = item;
        if (item.children != null && item.children.length > 0) {
            setChapterChildrenMap(item.children, map, item);
        }
    }
}
</script>
<style>
:root {
    --custom-menu-item-height: 36px;
    --custom-menu-item-font-size: 16px;
    --navigation-bar-span-height: 32px;
}

.doc_share_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.doc_share_container>.el-container {
    height: 100%;
}

.doc_share_container>.el-container>.el-header {
    padding: 0px;
    border-bottom: 1px solid var(--el-border-color);
}

.doc_share_container .header_span {
    display: flex;
    padding: 5px;
    width: calc(100% - 10px);
    height: calc(100% - 10px);
    align-items: center;
}
.header_span .header_title {
    display: flex;
    width: auto;
    height: 100%;
    margin-left: 10px;
    align-items: center;
    font-size: 24px;
    color: #303133;
    cursor: default;
}
.doc_left_scroll {
    border-right: 1px solid var(--el-border-color);
}
.menu_top_span {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: calc(100% - 1px);
    border-right: 1px solid var(--el-border-color);
}
.menu_top_span .menu_top_span_item {
    display: flex;
    flex-direction: row;
    justify-content: start;
    align-items: center;
}
.menu_top_span .bt_menu_search {
    width: 80%;
    height: 20px;
    margin-top: 10px;
    padding: 5px 12px 5px 12px;
    border-radius: 8px;
    line-height: 20px;
    background-color: #f4f4f5;
    color: #b1b3b8;
    cursor: pointer;
}
.menu_top_span .bt_menu_search span {
    margin-left: 16px;
    font-size: 14px;
}
.menu_top_span .menu_top_catalog {
    justify-content: space-between;
    width: 100%;
    height: 36px;
    margin-top: 8px;
    color: var(--el-text-color-primary);
    font-size: 16px;
}
.menu_top_span .menu_top_catalog > span {
    margin-left: var(--el-menu-level-padding);
    font-size: 18px;
    font-weight: 400;
    cursor: default;
}
.menu_top_span .menu_top_catalog .menu_top_catalog_bt {
    display: flex;
    flex-direction: row;
    margin-right: var(--el-menu-level-padding);
    cursor: pointer;
    font-weight: 100;
    color: #b1b3b8;
}
.menu_top_span .menu_top_catalog .menu_top_catalog_bt > span {
    display: block;
    width: 18px;
    height: 18px;
    margin-left: 12px;
    line-height: 18px;
    cursor: pointer;
}
.doc_menu {
    border: 0px;
}

.doc_menu .el-menu-item {
    height: var(--custom-menu-item-height);
    font-size: var(--custom-menu-item-font-size);
}

.doc_menu .el-sub-menu__title {
    height: var(--custom-menu-item-height);
    font-size: var(--custom-menu-item-font-size);
}

.navigation_bar_span {
    display: flex;
    padding-left: 8px;
    width: calc(100% - 8px);
    height: var(--navigation-bar-span-height);
    align-items: center;
    border-bottom: 1px solid var(--el-border-color);
}
.navigation_bar_span .menu_bt_span {
    display: none;
}

.content_span {
    padding: 0px 0px 0px 0px;
    min-height: 320px;
    height: auto;
    z-index: 100;
}
.show_span_pc {
    display: block;
}
.show_span_mobile {
    display: none;
}
.show_span_mobile .el-drawer__body{
    padding: 0px 0px 0px 0px;
}
.doc_menu_bottom {
    display: flex;
    width: 100%;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    color: #73767a;
}
.search_dialog_span {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 360px;
}
.search_dialog_span .search_dialog_top {
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 30px;
}
.search_dialog_span .search_dialog_center {
    display: flex;
    margin-top: 10px;
    width: 100%;
    height: 320px;
}
.search_dialog_center .search_list {
    width: 100%;
    height: auto;
}
.search_list .search_list_item {
    display: flex;
    flex-direction: column;
    padding: 0px 8px 0px 8px;
    margin-bottom: 5px;
    width: calc(100% - 16px);
    min-height: 30px;
    align-items: center;
    cursor: pointer;
    border-radius: 5px;
}
.search_list .search_list_item:hover {
    background: #dedfe0;
}
.search_list_item .search_doc_span {
    display: flex;
    width: 100%;
    justify-content: space-between;
    font-size: 16px;
}
.search_doc_span .search_doc_span_item {
    height: 32px;
    line-height: 32px;
    color: #909399;
}
.search_doc_span .search_doc_title {
    width: calc(100% - 170px);
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.search_doc_span .search_doc_date {
    width: 160px;
}
.search_doc_title_ico {
    color: #79bbff;
}
.search_list_item .search_doc_result {
    margin-bottom: 5px;
    width: 100%;
    justify-content: start;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-size: 16px;
    color: #909399;
}
.search_doc_result em {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}
@media screen and (max-width: 960px) {
    .show_span_pc {
        display: none;
    }
    .show_span_mobile {
        display: block;
    }
    .doc_left_scroll{
        border: none;
    }
    .navigation_bar_span .menu_bt_span {
        display: flex;
        width: auto;
        height: 100%;
        align-items: center;
    }
    .content_span {
        padding: 0px 0px 0px 0px;
        min-height: 320px;
        height: auto;
    }
    .menu_top_span {
        display: flex;
        justify-content: center;
        width: 100%;
        border: none;
    }
    .search_doc_span .search_doc_title {
        width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .search_doc_span .search_doc_date {
        display: none;
    }
}
</style>